<?php

/**
 * user actions.
 *
 * @package    FirstSeec
 * @subpackage user
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class userActions extends sfActions
{
	//
	//	Profile
	//
	public function executeProfile(sfWebRequest $request) {
//		if($request->getParameter('id'))
//		{
//			$this->msg = 'Friend\'s profile';
//			$this->seec_user = Doctrine::getTable('SeecUser')
//			->find(array($request->getParameter('id')));
//		}
//		else
//		{
//			$this->msg = 'Profile without category';
//			$this->seec_user = Doctrine::getTable('SeecUser')
//			->find($this->getUser()->getAttribute('user_id'));
//		}
//		$this->forward404Unless($this->seec_user);

	}
	public function executeShowProfile(sfWebRequest $request) {	
		if (!$this->getUser()->isAuthenticated()) {
			$data = '{"redirect":"login"}';
			return $this->renderPartial('response', array('json_data' => $data));
		}
				
		$userID = $this->getUser()->getAttribute('user_id');

		$query = Doctrine_Query::create()
		->select('*')
		->from ('SeecUser SU')
		->where('SU.id = ?', $userID)->execute();
		$users = $query->toArray();

		$userName = $users[0]["username"];
		$lastName = $users[0]["lastname"];
		$firstName = $users[0]["firstname"];

		$query = Doctrine_Query::create()
		->select('*')
		->from ('SeecUserCategory SUC')
		->where('SUC.user_id = ?', $userID)->execute();
		$userCategories = $query->toArray();
		$userCateNum = count($userCategories);

		$formatData = "{\"profile\": ";
		$formatData .= "{\"userid\":\"";
		$formatData .= $userID;
		$formatData .= "\", \"username\":\"";
		$formatData .= $userName;
		$formatData .= "\", \"lastname\":\"";
		$formatData .= $lastName;
		$formatData .= "\", \"firstname\":\"";
		$formatData .= $firstName;
		$formatData .= "\", \"category\":[";

		for ($j=0; $j<$userCateNum; $j++) {
			$formatData .= "\"";
			$formatData .= $userCategories[$j]["category_name"];
			$formatData .= "\",";
		}
		if ($userCateNum!==0) {
			$formatData = substr($formatData, 0, -1);
		}
		$formatData .= "]}}";

		return $this->renderPartial('response', array('json_data' => $formatData));
 
	}

	
	
	//
	//	Login
	//
	public function executeLogin(sfWebRequest $request)
	{			
		//for test
		//$test = new SeecQuestion();
		//$testres = $test->unansweredQuestion(3);
		//$testres = $test->getPotentialUser("Life");
		//$testres = $test->saveQuestion("nba playoff : suns vs blazers guess which team will win the game");
		//$testres = $test->askedQuestion(2);
		//$testres = $test->getResultsBySearchEngine("where can i get the cheapest cosmetics for my girlfriend? but i donnot want those with shallow quality. i am sure there are some good stores in 5th avenu.");
		//print_r ($testres);
		$this->form = new SeecUserLoginForm();
	}

	public function executeLoginCheck(sfWebRequest $request)
	{
		$this->forward404Unless($request->isMethod(sfRequest::POST));

		$this->form = new SeecUserLoginForm();

		$this->processForm($request, $this->form, true);

		$this->setTemplate('login');
	}

	
	//
	//	Logout
	//
	public function executeLogout(sfWebRequest $request) {
		if ($this->getUser()->isAuthenticated()) {
			$this->getUser()->setAuthenticated(false);	
		}
		$this->redirect('http://localhost:8080/frontend_dev.php/user/login');
	}
	
	//
	//	Register
	//
	public function executeRegister(sfWebRequest $request) {
	}
	
	public function executeRegisterCheck(sfWebRequest $request) {
		$username = $request->getParameter('username');
		$password = $request->getParameter('password');
		$lastname = $request->getParameter('lastname');
		$firstname = $request->getParameter('firstname');
		$strCategory = $request->getParameter('category');
		
		$strCategory = substr($strCategory, 0, strlen($strCategory) - 1);
		$categorys = preg_split('/,/', $strCategory); 	
		
		$user = new SeecUser();			//save personal information
		$user->username = $username;
		$user->password = $password;
		$user->lastname = $lastname;
		$user->firstname = $firstname;

		$users = Doctrine_Query::create()
			->from('SeecUser u')
			->where('u.username = ?', $username)
			->execute();

		if ($users->count() == 1) {
			return $this->renderPartial('response', array('json_data' => '{"warning":"Email has been used"}'));
		} else {
			$user->save();
		
			foreach ($categorys as $c) {
				$scs = Doctrine_Query::create()
					->from('SeecCategory C')
					->where('C.name = ?', $c)
					->execute();
				
				$sc = $scs[0];
				
				$uc = new SeecUserCategory();
				$uc->setSeecUser($user);
				$uc->setSeecCategory($sc);
				$uc->save();
			}
			
			
			$this->getUser()->setAttribute('user_id', $user->getId());
			$this->getUser()->setAttribute('user_name', $user->getUsername());
			$this->getUser()->setAuthenticated(true);

			return $this->renderPartial('response', array('json_data' => '{"redirect":"../question/ask"}'));
		}
		
		// TODO: redirect to profile or ask
		
	}
	
	protected function processForm(sfWebRequest $request, sfForm $form, $isLogin = false)
	{
		if ($isLogin)
		{
			// TODO, Haomin: Here, we should have a better way to express
			//	 "$request->getPostParameter('seec_user[username]');"
			$username = $request->getPostParameter('seec_user[username]');
			$password = $request->getPostParameter('seec_user[password]');

			$users = Doctrine_Query::create()
			->from('SeecUser u')
			->where('u.username = ? AND u.password = ?', array($username, $password))
			->execute();

			if ($users->count() == 1)
			{
				$user = $users[0];
				$this->getUser()->setAttribute('user_id', $user->getId());
				$this->getUser()->setAttribute('user_name', $user->getUsername());
				$this->getUser()->setAuthenticated(true);
				
				$this->redirect('question/ask');
			}
			else
			{
				// TODO: give a "wrong username and password" hint.
				//	but, how to?
			}
		}
		else
		{
			$form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
			if ($form->isValid())
			{
				$seec_user = $form->save();

				$this->redirect('user/edit?id='.$seec_user->getId());
			}
			else return;
		}
	}
}
